package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.LogService;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SupplierServiceImpl implements SupplierService {
    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private LogService logService;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String supplierName) {
        Map<String,Object> map = new HashMap<>();
        //模糊查询供应商列表
        List<Supplier> supplierList =  supplierDao.selectLists(page,rows,supplierName);

        Integer count = supplierDao.getSupplierCount(supplierName);
        map.put("total",count);
        map.put("rows",supplierList);
        logService.save(new Log(Log.SELECT_ACTION,"分页查询供应商信息"));
        return map;
    }

    @Override
    public ServiceVO save(Supplier supplier) {
        //查看id是否存在,不存在就保存
        if (supplier.getSupplierId() == null){

            supplierDao.addSupplier(supplier);
            logService.save(new Log(Log.INSERT_ACTION,"新增供应商"+supplier.getSupplierId()));
        }else {
            supplierDao.update(supplier);
            logService.save(new Log(Log.INSERT_ACTION,"更新供应商"+supplier.getSupplierId()));
        }

        //存在进行修改
        //存在返回false
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }

    @Override
    //ids ={3,4,5};  [3,2,4]
    public ServiceVO deleteSupplier(String ids) {

        String[] sid = ids.split(",");

        List<Integer> idList = new ArrayList<>();
        for (String s : sid) {
            idList.add(Integer.parseInt(s));
        }
       /* List<String> idList = Arrays.asList(sid);*/
        for (Integer id : idList) {
            logService.save(new Log(Log.DELETE_ACTION,"删除供应商:"+supplierDao.getSupplierById(id).getSupplierName()));
        }


        supplierDao.deleteSupplier(idList);
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }
}
